package myaction.admin.teacherinfo;

import myutil.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class TeacherAddAction extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String t_id = request.getParameter("t_id");
        String t_name = request.getParameter("t_name");
        String t_username = request.getParameter("t_username");
        String t_password = request.getParameter("t_password");
        try {
            Connection cn = DbUtil.getConn();
            String sql1 = "select t_id from t_teachers where t_id = " + t_id + ";";
            Statement stmt = cn.createStatement();
            ResultSet rs = stmt.executeQuery(sql1);
            if (rs.next()) {
                rs.close();
                stmt.close();
                cn.close();
                request.setAttribute("CourseRepeat", "<script>alert('编号为\" + t_id + \"的教师已存在！')</script>");
                request.getRequestDispatcher("TeacherAddAction").forward(request, response);
            } else {
                    String sql = "insert into t_teachers(t_id,t_name,t_username,t_password) values(?,?,?,?)";
                    PreparedStatement ps = cn.prepareStatement(sql);
                    ps.setString(1, t_id);
                    ps.setString(2, t_name);
                    ps.setString(3, t_username);
                    ps.setString(4, t_password);
                    ps.executeUpdate();
                    ps.close();
                    cn.close();
                    response.sendRedirect("admin/adminmain.jsp");

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        response.sendRedirect("admin/adminmain.jsp");
    }
}



